<template>
  <div class="home">
    <h1>{{ partyInfo.partyTime + titleText }}</h1>
    <div class="operate">
      <el-button type="warning" @click="reloadData">刷新</el-button>
      <el-date-picker
          @change="reloadData"
          ref="partyTime"
          v-model="partyInfo.partyTime"
          type="year"
          format="YYYY"
          value-format="YYYY"
          placeholder="选择年度"
          style="width: 200px"/>
    </div>
    <div id="bar" style="width: 100%; height: 300px"></div>
    <div id="radar" style="width: 100%; height: 400px"></div>
    <h1>严禁发生的行为清单</h1>
    <el-table class="party" :data="partyForbid" border
              :header-cell-style="{'text-align': 'center'}"
              empty-text="暂无严禁发生的行为" style="width: 100%;height: auto;overflow: auto">
      <el-table-column type="index" label="序号" align="center" width="80"/>
      <el-table-column prop="partyName" label="支部名称" align="center" min-width="100"/>
      <el-table-column prop="partyTime" label="年度" align="center" min-width="60"/>
      <el-table-column prop="execute3" label="严禁发生的行为" align="left" min-width="100">
        <template #default="scope">
          <div v-for="(val) in orderExecute(scope.row.execute3)">
            {{JSON.parse(val).data}}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="execute3" label="备注" align="left" min-width="100">
        <template #default="scope">
          <div v-for="(val,key) in orderExecute(scope.row.execute3)">
            {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">

export default {
  name: "Home"
}
</script>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {EchartsUtils} from "@/utils/EchartsUtils";
import {ECHARTS_BAR, ECHARTS_RADAR} from "@/views/constants";
import {TimeUtils} from "@/utils/TimeUtils";
import {
  IEChartParty, IEChartRadar, IEChartRadarSeriesData,
  IEChartSeries,
  IEChartXAxis,
  IExecute, IForbid,
  IParty,
  ITypeNumber
} from "@/iwb/IParty";
import {getYearPartyBuilding} from "@/api/party";

const titleText = ref('年度党组织落实全面从严治党主体责任---评估情况');
const partyInfo = ref({} as IParty);
const totalCount = ref(0);
const partyBuilding = ref([] as Array<IParty>);
const echartParties = ref([] as Array<IEChartParty>);
let minRankUpdateId: number | undefined = undefined;
let myChart: any | undefined = undefined;
let myRadarChart: any | undefined = undefined;
const partyForbid = ref([] as Array<IForbid>);

const getMinRankUpdateId = (id: number) => {
  if (minRankUpdateId === undefined) {
    return id;
  }
  return minRankUpdateId > id ? id : minRankUpdateId;
}

const getAuthenticScore = (item: IParty, minId: number | undefined, oldScore: number) => {
  return item.id === minId || !oldScore ? item.score : oldScore;
}

const adjustScore = (score: number) => {
  return score > 90 ? '优秀': score > 80 ? '良好': score > 70 ? '一般' : '不力';
}

const orderExecute = (execute: Array<string>) => {
  if (execute) {
    return execute.sort();
  }
  return [];
}

/**
 * 获取信息
 * @param execute
 * @param evaluation
 */
const getExecute = (execute: Array<any>, evaluation: string): IExecute | undefined => {
  if (execute) {
    for (let i=0; i<execute.length; ++i) {
      const item = execute[i];
      const jsonExecute: IExecute = JSON.parse(item);
      if (jsonExecute.data === evaluation) {
        return jsonExecute;
      }
    }
  }
  return undefined;
}

const getBonusOrNegative = (oldBonus: Array<IExecute>, bonus: Array<IExecute>): Array<IExecute> => {
  return bonus && bonus.length > 0 ? bonus : oldBonus;
}

/**
 * 设置党建编辑基本信息
 * @param partyInfo
 */
const initPartyInfo = (partyInfo: Array<IParty>) => {
  if (partyInfo && partyInfo.length > 0) {
    const partyInfoMap = new Map();

    partyInfo.forEach((item: IParty) => {
      let itemArray = partyInfoMap.get(item.partyName);
      if (itemArray === undefined) {
        itemArray = [];
      }
      itemArray.push(item);
      partyInfoMap.set(item.partyName, itemArray);
    })

    /**
     * 遍历
     */
    echartParties.value = [];
    partyInfoMap.forEach((value: Array<IParty>, keyName) => {
      const partyTypeMap = new Map();
      /**
       * 统计每个支部的完成情况
       */
      const echartParty = {} as IEChartParty;
      echartParty.name = keyName;
      echartParty.type = [];
      echartParty.score = 0;

      value.forEach((item: IParty) => {
        partyTypeMap.set(item.partyType, item.partyType);
      })
      partyTypeMap.forEach((typeValue, typeKey) => {
        const typeNumber = {} as ITypeNumber;
        typeNumber.total = 0;
        typeNumber.checkNumber = 0;
        typeNumber.name = typeValue;
        value.filter(item => item.partyType === typeKey).forEach((item: IParty) => {
          echartParty.censorStatus = item.censorStatus;
          minRankUpdateId = getMinRankUpdateId(item.id);
          echartParty.score = getAuthenticScore(item, minRankUpdateId, echartParty.score);

          echartParty.bonus = getBonusOrNegative(echartParty.bonus, item.bonus);
          echartParty.negative = getBonusOrNegative(echartParty.negative, item.negative);
          item.evaluation1?.forEach((evaluation: string, index: number) => {
            typeNumber.total += 1;
            const evalua = index + 1 + '.' + evaluation;
            const execute = getExecute(item.execute1, evalua);
            if (execute) {
              typeNumber.checkNumber += 1;
            }
          })

          item.evaluation2?.forEach((evaluation: string, index: number) => {
            typeNumber.total += 1;
            const evalua = index + 1 + '.' + evaluation;
            const execute = getExecute(item.execute2, evalua);
            if (execute) {
              typeNumber.checkNumber += 1;
            }
          })

          item.evaluation3?.forEach((evaluation: string, index: number) => {
            typeNumber.total += 1;
            const evalua = index + 1 + '.' + evaluation;
            const execute = getExecute(item.execute3, evalua);
            if (execute) {
              typeNumber.checkNumber -= 1;
              const forbid = {} as IForbid;
              forbid.partyName = item.partyName;
              forbid.partyTime = item.partyTime;
              forbid.partyType = item.partyType;
              forbid.evaluation3 = item.evaluation3;
              forbid.execute3 = item.execute3;
              partyForbid.value.push(forbid)
            } else {
              typeNumber.checkNumber += 1;
            }
          })
        })
        echartParty.type.push(typeNumber);
      })
      echartParties.value.push(echartParty);
    })
  }
}

const reloadData = () => {
  partyBuilding.value = [];
  echartParties.value = [];
  partyForbid.value = [];
  minRankUpdateId = undefined;
  const xAxis = [] as Array<any>;
  const legend = {data: [] as Array<string>};
  const series = [] as Array<any>;
  const radar = {indicator: [] as Array<IEChartRadar>, init: false};
  const radarLegend = {data: [] as Array<string>}
  const radarSeries = [] as Array<any>;
  const radarSeriesData = {
        name: 'Budget vs spending',
        type: 'radar',
        data: [] as Array<any>,
      };

  getYearPartyBuilding(partyInfo.value.partyTime).then((res: any) => {
    totalCount.value = res.data.total;
    res.data.buildings.forEach((item: IParty) => {
      item.scoreLabel = adjustScore(item.score);
    })
    partyBuilding.value = res.data.buildings;
    initPartyInfo(partyBuilding.value);

    const echartXAxis = {} as IEChartXAxis;
    echartXAxis.data = [];
    echartXAxis.type = 'category';
    echartXAxis.axisTick = { show: false };
    const seriesMap = new Map();
    echartParties.value.forEach((item: IEChartParty) => {
      const radarObjectSeriesData = {} as IEChartRadarSeriesData;
      echartXAxis.data.push(item.name+'[' + adjustScore(item.score)+'][' + item.censorStatus+']');
      radarLegend.data.push(item.name);
      radarObjectSeriesData.name = item.name;
      radarObjectSeriesData.value = [];
      item.type.forEach((type: ITypeNumber) => {
        let seriesData = seriesMap.get(type.name);
        if (!seriesData) {
          seriesData = {} as IEChartSeries;
          seriesData.name = type.name;
          seriesData.type = 'bar';
          seriesData.emphasis = { focus: 'series' };
          seriesData.data = [];
        }
        seriesData.data.push(type.checkNumber);
        seriesMap.set(type.name, seriesData);
        if (!radar.init) {
          radar.indicator.push({name: type.name, max: type.total})
        }
        radarObjectSeriesData.value.push(type.checkNumber);
      })
      radar.init = true;
      radarSeriesData.data.push(radarObjectSeriesData);
    });
    seriesMap.forEach(value => {
      series.push(value);
      legend.data.push(value.name);
    });
    xAxis.push(echartXAxis);

    if (myChart) {
      ECHARTS_BAR.xAxis = xAxis.length === 0 ? ECHARTS_BAR.xAxis : xAxis;
      // @ts-ignore
      ECHARTS_BAR.legend.data = legend.data;
      ECHARTS_BAR.series = series;
      myChart.clear();
      myChart.setOption(ECHARTS_BAR, true);
    }

    /**
     * 雷达图
     */
    if (myRadarChart) {
      radarSeries.push(radarSeriesData);
      // @ts-ignore
      ECHARTS_RADAR.legend.data = radarLegend.data;
      ECHARTS_RADAR.radar = radar;
      ECHARTS_RADAR.series = radarSeries;
      myRadarChart.clear();
      myRadarChart.setOption(ECHARTS_RADAR, true);
    }
  })
}

onMounted(() => {
  partyInfo.value.partyTime = TimeUtils.getCurrentYear().toString();
  myChart = EchartsUtils.initOption('bar', ECHARTS_BAR);
  myRadarChart = EchartsUtils.initOption('radar', ECHARTS_RADAR);
  reloadData();
})
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  .operate {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
}
</style>